package com.blue.base.common.utils.http;

import com.blue.base.common.exception.BaseException;
import lombok.extern.slf4j.Slf4j;
import org.springframework.http.*;
import org.springframework.util.MultiValueMap;
import org.springframework.web.client.RestTemplate;

/**
 * @author liulei
 * @version 1.0
 */
@Slf4j
public class HttpUtils {
    /**
     * 向目的URL发送post请求
     *
     * @param url    目的url
     * @param t      目标结果类
     * @param params 发送的参数
     * @return t
     */
    public static <T> T postSend(String url, Class<T> t, MultiValueMap<String, Object> params) {
        RestTemplate restTemplate = new RestTemplate();
        HttpHeaders headers = new HttpHeaders();
        HttpMethod method = HttpMethod.POST;
        // 以表单的方式提交
        headers.setContentType(MediaType.APPLICATION_FORM_URLENCODED);
        //将请求头部和参数合成一个请求
        HttpEntity<MultiValueMap<String, Object>> requestEntity = new HttpEntity(params, headers);
        //执行HTTP请求，将返回的结构使用ResultVO类格式化
        try {
            ResponseEntity<T> response = restTemplate.exchange(url, method, requestEntity, t);
            if (response.getStatusCode() != HttpStatus.OK) {
                throw new RuntimeException("POST请求服务器异常，请检查服务");
            }
            return response.getBody();
        } catch (Exception e) {
            log.error("http post远程调用异常", e);
        }
        throw new BaseException(800, "http post远程调用异常");
    }

    /**
     * 向目的URL发送get请求
     *
     * @param urlWithParam 目的url带&符号的参数
     * @param t            目标结果类
     * @return t
     */
    public static <T> T getSend(String urlWithParam, Class<T> t, HttpHeaders headers) {
        RestTemplate restTemplate = new RestTemplate();
        try {
            ResponseEntity<T> response = restTemplate.exchange(urlWithParam, HttpMethod.GET, new HttpEntity(headers), t);
            if (response.getStatusCode() != HttpStatus.OK) {
                throw new RuntimeException("GET请求服务器内部异常，请检查远程服务");
            }
            return response.getBody();
        } catch (Exception e) {
            log.error("http get远程调用异常", e);
        }
        throw new BaseException(800, "http get远程调用异常");
    }

}
